<template>
  <div class="courier-list-container">
    <!-- 搜索和筛选区域 -->
    <div class="search-filter-bar">
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-input
          v-model="searchQuery"
          placeholder="搜索配送员姓名、手机号或工号"
          class="search-input"
          clearable
          @clear="handleSearch"
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      
      <!-- 筛选区域 -->
      <div class="filter-section">
        <el-select v-model="filterStatus" placeholder="工作状态" clearable @change="handleSearch" class="filter-item">
          <el-option label="在职" value="active" />
          <el-option label="休假" value="onLeave" />
          <el-option label="离职" value="inactive" />
        </el-select>
        
        <el-select v-model="filterArea" placeholder="所属区域" clearable @change="handleSearch" class="filter-item">
          <el-option v-for="area in areaOptions" :key="area.value" :label="area.label" :value="area.value" />
        </el-select>
        
        <el-select v-model="filterRating" placeholder="评分筛选" clearable @change="handleSearch" class="filter-item">
          <el-option label="4.5分以上" value="4.5" />
          <el-option label="4分以上" value="4" />
          <el-option label="3.5分以上" value="3.5" />
          <el-option label="3分以上" value="3" />
        </el-select>
      </div>
      
      <!-- 操作按钮区域 -->
      <div class="action-section">
        <el-button type="primary" @click="$emit('add-courier')" class="action-button">
          <el-icon><Plus /></el-icon>新增配送员
        </el-button>
        <el-button type="success" @click="handleExport" class="action-button">
          <el-icon><Download /></el-icon>导出数据
        </el-button>
      </div>
    </div>

    <!-- 列表区域 -->
    <div class="table-container">
      <el-table
        :data="filteredCouriers"
        style="width: 100%"
        @row-click="handleRowClick"
        v-loading="loading"
        border
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column type="index" width="60" align="center" />
        <el-table-column prop="avatar" label="头像" width="80" align="center">
          <template #default="scope">
            <el-avatar size="small" :src="scope.row.avatar">
              {{ scope.row.name.substring(0, 1) }}
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="工号" min-width="100" align="center" />
        <el-table-column prop="name" label="姓名" min-width="90" align="center" />
        <el-table-column prop="phone" label="手机号" min-width="130" />
        <el-table-column prop="area" label="所属区域" min-width="110" />
        <el-table-column prop="status" label="状态" min-width="90" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)" size="small">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="rating" label="评分" min-width="160" align="center">
          <template #default="scope">
            <div class="rating-display">
              <el-rate
                v-model="scope.row.rating"
                disabled
                text-color="#ff9900"
                :max="5"
                :allow-half="true"
                :colors="['#F7BA2A', '#F7BA2A', '#F7BA2A']"
                style="display: inline-flex; justify-content: center"
                :score-template="scope.row.rating"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="deliveryCount" label="总派送量" min-width="100" align="center" sortable />
        <el-table-column prop="onTimeRate" label="准时率" min-width="100" align="center" sortable>
          <template #default="scope">
            <span>{{ scope.row.onTimeRate }}%</span>
          </template>
        </el-table-column>
        <el-table-column prop="joinDate" label="入职日期" min-width="120" align="center" sortable />
        <el-table-column fixed="right" label="操作" width="180" align="center">
          <template #default="scope">
            <div class="action-buttons">
              <el-button link type="primary" @click.stop="$emit('edit-courier', scope.row)" size="small">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button link type="primary" @click.stop="$emit('view-courier', scope.row)" size="small">
                <el-icon><View /></el-icon>详情
              </el-button>
              <el-popconfirm
                title="确定要删除此配送员吗？"
                @confirm="handleDelete(scope.row)"
                @click.stop
              >
                <template #reference>
                  <el-button link type="danger" size="small">
                    <el-icon><Delete /></el-icon>删除
                  </el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCouriers"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { Search, Plus, Download, Edit, View, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 页面状态
const loading = ref(false)
const searchQuery = ref('')
const filterStatus = ref('')
const filterArea = ref('')
const filterRating = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalCouriers = ref(0)

// 区域选项
const areaOptions = [
  { value: '华东区', label: '华东区' },
  { value: '华南区', label: '华南区' },
  { value: '华北区', label: '华北区' },
  { value: '西南区', label: '西南区' },
  { value: '西北区', label: '西北区' },
  { value: '东北区', label: '东北区' }
]

// 模拟数据
const couriers = reactive([
  {
    id: 'PS10001',
    name: '张三',
    phone: '13812345678',
    area: '华东区',
    status: 'active',
    rating: 4.8,
    deliveryCount: 1283,
    onTimeRate: 98.5,
    joinDate: '2022-06-15',
    avatar: ''
  },
  {
    id: 'PS10002',
    name: '李四',
    phone: '13912345678',
    area: '华南区',
    status: 'active',
    rating: 4.3,
    deliveryCount: 982,
    onTimeRate: 95.2,
    joinDate: '2022-07-20',
    avatar: ''
  },
  {
    id: 'PS10003',
    name: '王五',
    phone: '13712345678',
    area: '华北区',
    status: 'onLeave',
    rating: 4.5,
    deliveryCount: 876,
    onTimeRate: 97.3,
    joinDate: '2022-08-05',
    avatar: ''
  },
  {
    id: 'PS10004',
    name: '赵六',
    phone: '13612345678',
    area: '西南区',
    status: 'inactive',
    rating: 3.8,
    deliveryCount: 543,
    onTimeRate: 92.1,
    joinDate: '2023-01-10',
    avatar: ''
  }
])

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    active: '在职',
    onLeave: '休假',
    inactive: '离职'
  }
  return statusMap[status] || status
}

// 获取状态标签类型
const getStatusType = (status) => {
  const typeMap = {
    active: 'success',
    onLeave: 'warning',
    inactive: 'info'
  }
  return typeMap[status] || ''
}

// 筛选后的配送员列表
const filteredCouriers = computed(() => {
  // 实际应用中，这里应该是通过API获取数据，而不是前端筛选
  return couriers.filter(courier => {
    const matchesSearch = searchQuery.value ? 
      courier.name.includes(searchQuery.value) || 
      courier.phone.includes(searchQuery.value) || 
      courier.id.includes(searchQuery.value) : true
    
    const matchesStatus = filterStatus.value ? courier.status === filterStatus.value : true
    const matchesArea = filterArea.value ? courier.area === filterArea.value : true
    const matchesRating = filterRating.value ? courier.rating >= parseFloat(filterRating.value) : true
    
    return matchesSearch && matchesStatus && matchesArea && matchesRating
  })
})

// 点击行事件
const handleRowClick = (row) => {
  emit('view-courier', row)
}

// 删除配送员
const handleDelete = (row) => {
  // 实际应用中，这里应该调用API删除数据
  const index = couriers.findIndex(c => c.id === row.id)
  if (index !== -1) {
    couriers.splice(index, 1)
    ElMessage.success('删除成功')
  }
}

// 导出数据
const handleExport = () => {
  ElMessage.success('数据导出中，请稍候...')
  // 实际应用中，这里应该调用API导出数据
  setTimeout(() => {
    ElMessage.success('数据已导出')
  }, 1500)
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  // 实际应用中，这里应该调用API重新获取数据
}

// 分页相关处理
const handleSizeChange = (size) => {
  pageSize.value = size
  // 实际应用中，这里应该调用API重新获取数据
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  // 实际应用中，这里应该调用API重新获取数据
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 实际应用中，这里应该调用API获取数据
    // const { data } = await api.getCouriers({
    //   page: currentPage.value,
    //   pageSize: pageSize.value,
    //   status: filterStatus.value,
    //   area: filterArea.value,
    //   rating: filterRating.value,
    //   query: searchQuery.value
    // })
    // couriers = data.list
    // totalCouriers.value = data.total

    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    totalCouriers.value = couriers.length
  } catch (error) {
    console.error('Failed to load couriers:', error)
    ElMessage.error('加载数据失败，请重试')
  } finally {
    loading.value = false
  }
}

// 定义组件事件
const emit = defineEmits(['add-courier', 'edit-courier', 'view-courier'])

// 初始化时加载数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.courier-list-container {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

/* 搜索和筛选区域样式 */
.search-filter-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 24px;
  align-items: center;
}

.search-section {
  flex: 1;
  min-width: 280px;
}

.search-input {
  width: 100%;
}

.filter-section {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.filter-item {
  width: 140px;
}

.action-section {
  display: flex;
  gap: 12px;
  margin-left: auto;
}

.action-button {
  display: flex;
  align-items: center;
}

.action-button .el-icon {
  margin-right: 6px;
}

/* 表格区域样式 */
.table-container {
  margin-bottom: 20px;
  overflow-x: auto;
}

.rating-display {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  flex-direction: column;
}

.rating-value {
  font-size: 13px;
  color: #606266;
  margin-top: 3px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  flex-wrap: nowrap;
  gap: 4px;
}

/* 分页区域样式 */
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .search-filter-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-section,
  .filter-section,
  .action-section {
    width: 100%;
  }
  
  .action-section {
    margin-left: 0;
    justify-content: flex-end;
  }
}
</style> 